import scala.math.random
import org.apache.spark.{SparkContext, SparkConf}

/**
 * 作者: LDL
 * 功能说明:
 * 创建日期: 2015/7/20 14:37
 */
object SparkPi{
  def main(args: Array[String]) {
    val conf = new SparkConf().setMaster("local").setAppName("SparkPi")

    val spark = new SparkContext(conf)

    val slices = if(args.length>0) args(0).toInt else 2
    val n = math.min(100000L * slices, Int.MaxValue).toInt // avoid overflow
    val count = spark.parallelize(1 until n,slices).map(i=>{
        val x = random * 2 - 1
        val y = random * 2 - 1
        if (x*x + y*y < 1) 1 else 0
      }).reduce(_+_)

    println("Pi is roughly " + 4.0 * count / n)
    spark.stop()
  }

}
